package com.kaishengit.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import com.kaishengit.entity.BookType;
import com.kaishengit.util.db.DBHelp;
import com.kaishengit.util.db.Page;
import com.kaishengit.util.db.RowMapper;

public class BookTypeDao {

	private DBHelp<BookType> db = new DBHelp<BookType>();
	
	public void save(BookType bookType) {
		String sql = "insert into t_booktype(id,typename) values(?,?)";
		db.executeSQL(sql, bookType.getId(),bookType.getTypename());
	}
	
	public void update(BookType bookType) {
		String sql = "update t_booktype set typename = ? where id = ?";
		db.executeSQL(sql, bookType.getTypename(),bookType.getId());
	}
	
	public void del(String id) {
		String sql = "delete from t_booktype where id = ?";
		db.executeSQL(sql, id);
	}
	
	public BookType findById(String id) {
		String sql = "select id,typename,createtime from t_booktype where id = ?";
		return db.executeQueryToObject(sql, new BookTypeRowMapper(), id);
	}
	
	public int count() {
		String sql = "select count(*) from t_booktype";
		return db.executeQuery(sql).intValue();
	}

	public List<BookType> findAll() {
		String sql = "select id,typename,createtime from t_booktype";
		return db.executeQueryToList(sql, new BookTypeRowMapper());
	}
	
	public Page<BookType> findByPage(int pageNum) {
		Page<BookType> page = new Page<BookType>(count(), pageNum);
		
		String sql = "select id,typename,createtime from t_booktype order by createtime desc limit ?,?";
		List<BookType> list =  db.executeQueryToList(sql, new BookTypeRowMapper(), page.getStart(),page.getPageSize());
		
		page.setList(list);
		return page;
	}
	
	private class BookTypeRowMapper implements RowMapper<BookType> {
		public BookType mapRow(ResultSet rs) throws SQLException {
			BookType bt = new BookType();
			bt.setCreatetime(rs.getString("createtime"));
			bt.setId(rs.getString("id"));
			bt.setTypename(rs.getString("typename"));
			return bt;
		}
	}
}
